﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObjects;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace GT5RemoteMobile
{
    public partial class AddOpponents : System.Web.UI.Page
    {
        string jsessionId;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["jsessionid"] == null)
                Response.Redirect("Default.aspx");
            jsessionId = Session["jsessionid"].ToString();

            if (!Page.IsPostBack)
            {
                if (Request.QueryString["addDrivers"] == null)
                    Response.Redirect("Default.aspx");
                string[] driversToAdd = Request.QueryString["addDrivers"].Split(',');

                foreach (string driver in driversToAdd)
                {
                    // hack to get a proper jsession id from gran-turismo.com
                    HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/api/gt5/remoterace/")) as HttpWebRequest;
                    //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
                    //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
                    profileRequest.Method = "POST";
                    StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

                    writer.Write("job=" + (int)RemoteRaceJobType.ADD_ENTRY + "&online_id=" + driver.Split('.')[0] +
                        "&driver_id=" + driver.Split('.')[1]);
                    writer.Close();
                    profileRequest.CookieContainer = new CookieContainer();
                    profileRequest.Headers.Add("Cookie", jsessionId);
                    profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
                    profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

                    //foreach (string c in Request.Cookies)
                    //{
                    //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
                    //    profileRequest.CookieContainer.Add(cookie);
                    //}
                    using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
                    {
                        // no response here
                    }
                }
            }
        }

        protected void GoRace(object sender, EventArgs e)
        {
            // READY TO RACE!! WHOOHOO!!
            // hack to get a proper jsession id from gran-turismo.com
            bool success = false;
            int retryCount = 5;
            RemoteRaceStatus status = new RemoteRaceStatus();
            while (!success)
            {
                try
                {
                    if (retryCount == 0)
                        break;
                    status = StartRace();
                    success = true;
                }
                catch (Exception)
                {
                    success = false;
                    retryCount--;
                }
            }

            
            // if the race hasn't started, the first thing we want is jobid = 6, otherwise, jobid = 8
            if (status.Status == RemoteRaceModeType.CHECK)
            {
                Response.Redirect("RaceStatus.aspx?raceStarted=false");
            }
            else if (status.Status == RemoteRaceModeType.RACE_MONITOR)
            {
                Response.Redirect("RaceStatus.aspx?raceStarted=true");
            }
        }

        private RemoteRaceStatus StartRace()
        {
            HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/api/gt5/remoterace/")) as HttpWebRequest;
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            profileRequest.Method = "POST";
            StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

            if (cbxSaveReplay.Checked)
                writer.Write("job=" + (int)RemoteRaceJobType.GO_RACE + "&replay_save=1");
            else
                writer.Write("job=" + (int)RemoteRaceJobType.GO_RACE + "&replay_save=0");
            writer.Close();
            profileRequest.CookieContainer = new CookieContainer();
            profileRequest.Headers.Add("Cookie", jsessionId);
            profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            //foreach (string c in Request.Cookies)
            //{
            //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
            //    profileRequest.CookieContainer.Add(cookie);
            //}
            RemoteRaceStatus status;
            using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string jsonData = reader.ReadToEnd();
                status = JsonConvert.DeserializeObject<RemoteRaceStatus>(jsonData);
            }
            return status;
        }
    }
}